package commands;

import user.Admin;
import user.User;
import messages.*;
import core.UserManager;
import event.*;
import exceptions.UserAlreadyExistsException;


/**
 * The AccountCreate command.
 * 
 * This command will handle AccountCreate messages.
 */
public class AccountCreateCommand extends Command {

	
	public AccountCreateCommand(Message message, User user) {
		super(message, user);
	}
	
	
	@Override
	public void execute() {
		UserManager userManager = controller.getUserManager();
		AccountCreateMessage message = (AccountCreateMessage) this.message;
		message.setSenderLogin(this.user.getLogin());
		
		String login = message.getLogin();
		String password = message.getPassword();
		String role = message.getRole();
		
		synchronized(userManager) {
			AccountCreationFailedMessage.ErrorCode errorCode = null;
			
			if (!(this.user instanceof Admin))
				errorCode = AccountCreationFailedMessage.ErrorCode.InsufficientPermissions;
			
			else if (login == null || login == "" || password == null || password == "" || !User.isValidRole(role))
				errorCode = AccountCreationFailedMessage.ErrorCode.InvalidParameters;
				
			else if (!userManager.isLoginAvailable(login))
				errorCode = AccountCreationFailedMessage.ErrorCode.UserAlreadyExists;
			
			if (errorCode != null) {
				controller.fireAccountCreationFailedEvent(new AccountCreationFailedEventArgs(
						this.user.getLogin(), new AccountCreationFailedMessage(message, errorCode)));
				
				return;
			}
			
			try {
				userManager.addUser(login, password, role);
			} catch (UserAlreadyExistsException e) {
				// This won't happen. Seriously!
			}
		}
		
		controller.fireAccountCreationSuccessful(new AccountCreationSuccessfulEventArgs(
				this.user.getLogin(), new AccountCreationSuccessfulMessage(this.user.getLogin(), login)));
	}
}
